<?php
class Admin_GroupsController extends Zend_Controller_Action
{
    protected $_flashMessenger = null;

    public function init()
    {
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->initView();
    }

	function indexAction()
	{
		$groups = Doctrine::getTable('Group');
		$this->view->groups = $groups->findAll();

		$this->view->flash = $this->_flashMessenger->getMessages();
	}

    function addAction()
    {
        $form = new GroupForm();
        $form->submit->setLabel('Add');
        $this->view->form = $form;

        if($this->_request->isPost())
        {
        	$formData = $this->_request->getPost();
        	if($form->isValid($formData))
        	{
        		$filtered_data = $form->getValues(true);

        		$group = new Group();
        		$group->merge($filtered_data);
        		$group->save();

        		$this->_flashMessenger->addMessage('Group created!');
        		$this->_helper->redirector('index');
        	}
        	else
        	{
        		$form->populate($formData);
        	}
        }
    }

    function editAction()
    {
        $form = new GroupForm();
        $form->submit->setLabel('Save');
        $this->view->form = $form;

        $group = $this->_findRecord();

        if($this->_request->isPost())
        {
            $formData = $this->_request->getPost();
            if($form->isValid($formData))
            {
            	$filtered_data = $form->getValues(true);

                $group->merge($filtered_data);
                $group->save();

                $this->_flashMessenger->addMessage('Group updated!');
                $this->_helper->redirector('index');
            }
            else
            {
                $form->populate($formData);
            }
        }
        else
        {
       		$form->populate($group->toArray());
        }
    }

    function deleteAction()
    {
        $group = $this->_findRecord();

        if($this->_request->isPost())
        {
        	$del = $this->_request->getPost('del');
        	
        	if ($del == 'Yes')
        	{
        		$group->unlink('users');
        		$group->delete();

        		$this->_flashMessenger->addMessage('Group deleted!');
        	}
        	$this->_helper->redirector('index');;
        }
        else
        {
       		$this->view->group = $group;
        }
    }
    
    /**
     * Finds record in database
     * 
     * @return Doctrine_Record
     */
    protected function _findRecord()
    {
        $id = (int) $this->_request->getParam('id');
        $record = Doctrine::getTable('Group')->find($id);
        if (!$record) throw new Zend_Controller_Dispatcher_Exception();

        return $record;
    }  
    
}
?>